<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>计算属性</title>
</head>
<body>
<div id="method">
    <div><span>总价：{{ prices }}</span></div>
    <div>
        <span>请输入姓名</span>
        <input placeholder="李 沁春" v-model="fullName">
        姓名：{{ fullName }}
        姓:{{ firstName }}
        名:{{ lastName }}
    </div>
    <div>
        <span>这是一段正常的话</span>
        <span>{{ reversedText() }}</span>
    </div>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
    new Vue({
        el: document.getElementById('method'),
        data: {
            package1: [
                {
                    name: 'iphone13',
                    price: 6549,
                    count: 2
                },
                {
                    name: 'ipadmini5',
                    price: 2500,
                    count: 100
                }
            ],
            package2: [
                {
                    name: 'apple',
                    price: 2888,
                    count: 5
                }
            ],
            firstName: '李',
            lastName: '沁春',
            text: '这是一段被反过来的话'

        },
        //method方法只要重新渲染，就会被调用
        methods: {
            reversedText: function () {
                return this.text.split('').reverse().join('');
            }
        },
        computed: {
            prices: function () {
                let prices = 0;
                for (let i = 0; i < this.package1.length; i++) {
                    prices += this.package1[i].price * this.package1[i].count;
                }
                for (let i = 0; i < this.package2.length; i++) {
                    prices += this.package2[i].price * this.package2[i].count;
                }
                return prices

            },
            fullName: {
                //每一个计算属性都包含一个get和set方法，当手动修改一个属性值时，会触发set方法。当获取一个属性值时，会触发get方法
                get: function () {
                    if (this.firstName == null) {
                        this.firstName = ''
                    }
                    if (this.lastName == null) {
                        this.lastName = ''
                        return this.firstName;
                    }
                    return this.firstName + ' ' + this.lastName;
                },
                set: function (newValue) {
                    let names = newValue.split(' ');
                    this.firstName = names[0];
                    if (names.length === 2) {
                        this.lastName = names[1]
                    }
                }
            }
        }
    })
</script>

</body>
</html>